package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.AdminUserService;
import com.cskaoyan.market.service.impl.AdminUserServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName AdminUserController
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/6/19 14:31
 * @Version V1.0
 **/
@WebServlet("/admin/user/*")
public class AdminUserController extends HttpServlet {

    private AdminUserService userService = new AdminUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/user/", "");
        if("list".equals(op)){
            list(req, resp);
        }
    }

    /**
     * 分页展示当前后台管理系统中的所有注册用户信息
     * 1、接收获取用户在页面中提交的请求参数信息
     * 2.到数据库中进行查询语句，查询出符合条件的结果
     * 3.返回结果，注意，需要分页返回
     * 参数的含义：
     * page：表示的是当前所在的页
     * limit：表示的是每页固定显示的数量
     * sort：表示的是页面数据排序的字段
     * order：上述的sort字段排除的规则，比如升序或者降序
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //请求参数应该如何来获取？只要满足key=value&key=value类型，那么======
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        //需要接收username和mobile，因为输入这两个参数，点击查询也是使用的是list接口
        String username = req.getParameter("username");
        String mobile = req.getParameter("mobile");

        //校验
        Integer page = null;
        Integer limit = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        }catch (Exception e){
            //return
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //调用service的代码逻辑即可
        List<MarketUser> userList = userService.list(page,limit,sort,order,username, mobile);
        //TODO 将userlist里面的数据通过json字符串响应出去
        //在执行分页查询时，调用方法时，需要调用oklist方法，而不是ok方法
        //如果你调用ok方法，那么无法获取诸如total、pages这些信息
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(userList)));
    }
}
